import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../../../../bean/bean_integral.dart';
import '../../../../bean/bean_user_account.dart';
import '../../../../net/dio_utils.dart';
import '../../../../utils/toast_utils.dart';
import '../../../common/common_loading_dialog.dart';
import '../../../common/common_nodata_widget.dart';
import 'mine_my_his_integral_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/13.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class MineMyScoreIntegralRecoderItemPage extends StatefulWidget {
  final String configId;
  final StreamController<String> dateSelectStream;

  MineMyScoreIntegralRecoderItemPage(
      {this.configId, this.dateSelectStream, Key key})
      : super(key: key);

  @override
  _MineMyScoreIntegralRecoderItemPageState createState() =>
      _MineMyScoreIntegralRecoderItemPageState();
}

class _MineMyScoreIntegralRecoderItemPageState
    extends State<MineMyScoreIntegralRecoderItemPage> {
  bool _isLoading = true;
  bool _isLoading2 = false;

  @override
  void initState() {
    super.initState();
    getMyScoreDataFunction();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return LoadingWidget();
    }
    if (_userIntegralStatBean == null) {
      return NoDataWidget(
        clickCallBack: () async {
          setState(() {
            _isLoading = true;
          });
          await getMyScoreDataFunction();
          ToastUtils.showToast("已刷新");
        },
      );
    }

    return RefreshIndicator(
      notificationPredicate: (ScrollNotification notifation) {
        //该属性包含当前ViewPort及滚动位置等信息
        ScrollMetrics scrollMetrics = notifation.metrics;
        if (scrollMetrics.minScrollExtent == 0) {
          return true;
        } else {
          return true;
        }
      },
      onRefresh: () async {
        setState(() {
          _isLoading2 = true;
        });
        await getMyScoreDataFunction();
        ToastUtils.showToast("已刷新");
        return true;
      },
      child: Column(
        children: [
          buildAvgScoreWidget(),
          Expanded(child: buildAnimatedSwitcher(context))
        ],
      ),
    );
  }

  ///AnimatedSwitcher 的基本使用
  AnimatedSwitcher buildAnimatedSwitcher(BuildContext context) {
    return AnimatedSwitcher(

        ///动画执行切换时间
        duration: const Duration(milliseconds: 200),

        ///动画构建器 构建指定动画类型
        transitionBuilder: (Widget child, Animation<double> animation) {
          //执行缩放动画
          return FadeTransition(child: child, opacity: animation);
        },

        ///执行动画的子 Widget
        ///只有子 Widget 被切换时才会触发动画
        child: buildMyScoreHisIntegralWidget());
  }

  buildMyScoreHisIntegralWidget() {
    if (_isLoading2) {
      return LoadingWidget();
    }
    if (_integralList.length == 0) {
      return Container(
        child: NoDataWidget(
          text: "暂无积分记录 点击刷新",
          clickCallBack: () async {
            setState(() {
              _isLoading2 = true;
            });
            await getMyScoreDataFunction();
            ToastUtils.showToast("已刷新");
          },
        ),
      );
    }
    return Card(
      child: Container(
        child: MineMyScoreHisIntegralPage(
            list: _integralList, configDetails: _configDetails),
        margin: EdgeInsets.all(4),
      ),
      elevation: 2.0,
    );
  }

  //平均分
  Widget buildAvgScoreWidget() {
    num totalScore = 0;

    num yestoday = 0;
    num weekDataNum = 0;
    num monthDataNum = 0;
    if (_userIntegralStatBean != null) {
      if (_userIntegralStatBean.yestodayData != null) {
        totalScore = _userIntegralStatBean.yestodayData.orderSettleAmt;
      }
      UserAccountBean yestodayData = _userIntegralStatBean.yestodayData;
      if (yestodayData != null) {
        yestoday = yestodayData.orderSettleAmt;
      }

      UserAccountBean weekData = _userIntegralStatBean.weekData;
      if (weekData != null) {
        weekDataNum = weekData.orderSettleAmt;
      }

      monthDataNum = _userIntegralStatBean.currMonthSettleMoney;
    }
    double scroeSize = 22;
    if (totalScore > 100) {
      scroeSize = 16;
    } else if (totalScore > 999) {
      scroeSize = 12;
    }
    return Card(
      elevation: 2.0,
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.only(left: 20, right: 20, bottom: 20, top: 10),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    children: [
                      Text(
                        "最近7天",
                        style: TextStyle(
                            color: Colors.red,
                            fontSize: 14,
                            fontWeight: FontWeight.w500),
                      ),
                      Text(
                        "${weekDataNum}分",
                        style: TextStyle(
                            color: Colors.red,
                            fontSize: 14,
                            fontWeight: FontWeight.w500),
                      ),
                      SizedBox(width: 12),
                      Text(
                        "本月获取",
                        style: TextStyle(
                            color: Colors.red,
                            fontSize: 14,
                            fontWeight: FontWeight.w500),
                      ),
                      SizedBox(
                        width: 12,
                      ),
                      Text(
                        "${monthDataNum}分",
                        style: TextStyle(
                            color: Colors.red,
                            fontSize: 14,
                            fontWeight: FontWeight.w500),
                      ),
                      SizedBox(width: 12),
                    ],
                  ),
                  SizedBox(
                    height: 2,
                  ),
                  Row(
                    children: [
                      Text(
                        "累计获取积分",
                        style: TextStyle(
                            color: Colors.black,
                            fontSize: 14,
                            fontWeight: FontWeight.w500),
                      ),
                      SizedBox(
                        width: 4,
                      ),
                      Text(
                        "${_userIntegralStatBean.totalCount}次",
                        style: TextStyle(
                            color: Colors.black,
                            fontSize: 14,
                            fontWeight: FontWeight.w500),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          "${_configDetails.showRemark}",
                          style: TextStyle(
                              color: Color(0xff666666),
                              fontSize: 12,
                              fontWeight: FontWeight.w400),
                        ),
                      ),
                      SizedBox(
                        width: 16,
                      ),
                      ClipOval(
                        child: Container(
                          alignment: Alignment.center,
                          color: Colors.blueGrey.withOpacity(0.2),
                          width: 86,
                          height: 86,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(
                                "$yestoday",
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: scroeSize,
                                ),
                              ),
                              Text(
                                "昨日积分",
                                style: TextStyle(
                                  fontWeight: FontWeight.w400,
                                  fontSize: 12,
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<IntegralStatBean> _integralList = [];
  UserAccountStateBean _userIntegralStatBean;
  IntegralStatBean _configDetails;

  Future<bool> getMyScoreDataFunction() async {
    Map<String, dynamic> monthMap = {
      "configId": widget.configId,
      "page": 1,
      "limit": 100,
    };
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.integralStatisticsRecoderDetails,
      queryParameters: monthMap,
    );

    if (statisRresponseInfo.success) {
      var responseData = statisRresponseInfo.data;
      if (statisRresponseInfo.success) {
        var responseData = statisRresponseInfo.data;
        if (responseData != null) {
          List list = responseData['list'];
          List<IntegralStatBean> newList = [];
          for (int i = 0; i < list.length; i++) {
            IntegralStatBean _rankStatBean = IntegralStatBean.fromJson(list[i]);
            newList.add(_rankStatBean);
          }
          _integralList = newList;

          if (responseData['userIntegral'] != null) {
            _userIntegralStatBean =
                UserAccountStateBean.fromMap(responseData['userIntegral']);
          } else {
            _userIntegralStatBean = null;
          }
          if (responseData['configDetails'] != null) {
            _configDetails =
                IntegralStatBean.fromJson(responseData['configDetails']);
          } else {
            _configDetails = null;
          }
        }
      }
    }
    _isLoading = false;
    _isLoading2 = false;
    if (mounted) {
      setState(() {});
    }

    return Future.value(true);
  }
}
